package com.cmes.system.web.controller;

import com.cmes.core.annotation.OperateLog;
import com.cmes.core.constant.enums.EnableStatus;
import com.cmes.core.domain.bo.IdsBO;
import com.cmes.core.utils.BeanUtils;
import com.cmes.system.api.bo.PermissionBO;
import com.cmes.system.core.entity.PermissionEntity;
import com.cmes.system.core.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Set;

/**
 * 部门管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/permission")
public class PermissionController {

    private final String MODULE = "权限管理";
    private final PermissionService permissionService;

    @PostMapping("tree")
    public List<PermissionEntity> tree() {
        return permissionService.tree();
    }

    @OperateLog(module = MODULE, businessType = "ADD")
    @PostMapping("add")
    public Long add(@RequestBody @Valid PermissionBO.AddBO bo) {
        PermissionEntity entity = BeanUtils.copyProperties(bo, new PermissionEntity());
        permissionService.canAdd(entity);
        entity.setSort(entity.getSort() == null ? 0 : entity.getSort());
        entity.setStatus(EnableStatus.ENABLE.getCode());
        permissionService.insert(entity);
        permissionService.removeCache();
        return entity.getId();
    }

    @OperateLog(module = MODULE, businessType = "UPDATE")
    @PostMapping("update")
    public Long update(@RequestBody @Valid PermissionBO.UpdateBO bo) {
        PermissionEntity entity = BeanUtils.copyProperties(bo, new PermissionEntity());
        permissionService.canUpdate(entity);
        permissionService.update(entity);
        permissionService.removeCache();
        return entity.getId();
    }

    @OperateLog(module = MODULE, businessType = "DELETE")
    @PostMapping("delete")
    public void delete(@RequestBody @Valid IdsBO bo) {
        Set<Long> ids = permissionService.canDelete(bo.getIds());
        permissionService.deletePermission(ids);
        permissionService.removeCache();
    }

    @OperateLog(module = MODULE, businessType = "DISABLE")
    @PostMapping("disable")
    public void disable(@RequestBody @Valid IdsBO bo) {
        Set<Long> ids = permissionService.canDisable(bo.getIds());
        permissionService.disable(ids);
        permissionService.removeCache();
    }

    @OperateLog(module = MODULE, businessType = "ENABLE")
    @PostMapping("enable")
    public void enable(@RequestBody @Valid IdsBO bo) {
        Set<Long> ids = permissionService.canEnable(bo.getIds());
        permissionService.enable(ids);
        permissionService.removeCache();
    }

}
